package com.tyk.bookstore.front.auth.manager;

import com.tyk.bookstore.front.common.other.code.msg.model.enume.MsgCodeType;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class AuthRedisManager {

    private final StringRedisTemplate redisTemplate;

    private static final String CODE_MSG_PREFIX = "auth:code:msg:";
    private static final int CODE_MSG_EXPIRE_TIME = 5;
    private static final TimeUnit CODE_MSG_EXPIRE_TIME_UNIT = TimeUnit.MINUTES;

    /**
     * 缓存登录验证码
     *
     * @param type       验证码类型
     * @param verifyCode 验证码凭证
     * @param principal  账号
     * @param code       验证码
     */
    public void cacheLoginMsgCode(MsgCodeType type, String verifyCode, String principal, String code) {
        redisTemplate.opsForValue().set(
                getLoginMsgCodeKey(type, verifyCode, principal),
                code,
                CODE_MSG_EXPIRE_TIME,
                CODE_MSG_EXPIRE_TIME_UNIT
        );
    }


    /**
     * 获取登录消息验证码
     *
     * @param type       登录类型
     * @param verifyCode 验证码凭证
     * @return 主体+验证码
     */
    public String getLoginMsgCode(MsgCodeType type, String verifyCode, String principal) {
        return redisTemplate.opsForValue().get(
                getLoginMsgCodeKey(type, verifyCode, principal)
        );
    }

    /**
     * 获取登录验证码的key
     *
     * @param type       登录类型
     * @param verifyCode 验证码凭证
     * @param principal  账号
     * @return 登录验证码的key
     */
    private String getLoginMsgCodeKey(MsgCodeType type, String verifyCode, String principal) {
        return CODE_MSG_PREFIX + type.name() + ":" + verifyCode + ":" + principal;
    }
}
